package com.watson;


import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static com.watson.fragment.HomeFragment.U_DEPOT_ID;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.watson.activity.Details2Activity;
import com.watson.activity.KuwActivity;
import com.watson.activity.TaskDetailsActivity;
import com.watson.http.CommonHttpConsts;
import com.watson.http.HttpCallbackData;
import com.watson.http.HttpClient;
import com.watson.utils.DialogUitl;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;
import com.watson.utils.ToastUtil;
import com.watson.view.AndroidWorkaround;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public abstract class BaseActivity extends AppCompatActivity {
    protected Context mContext;
    protected boolean isConnected;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置只竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mContext = this;
        if (AndroidWorkaround.checkDeviceHasNavigationBar(this)) { //适配华为手机虚拟键遮挡tab的问题
            AndroidWorkaround.assistActivity(findViewById(android.R.id.content));//需要在setContentView()方法后面执行
        }
        requestPermissions(99);
        ScreenManager.getScreenManager().addActivity(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        MyApp.setOnImportListener(new MyApp.OnImportListener() {
            @Override
            public void showToastMessage(String message) {
                LogUtils.e("TAG", "message===-------======>" + message);
                String barcoderules = SPUtils.get(mContext, "barcoderules", "") + "";
                if (!StringUtils.isEmpty(barcoderules) && message.contains("L:")) {
//                    String R_Auth_Code = SPUtils.get(mContext, "auth", "") + "";
//                    if (R_Auth_Code.contains("ADD_WarehouseEntryTask")) {
                    add_WMS_WarehouseEntryTask(message.replace("L:", ""));
//                    } else {
//                        Intent intent = new Intent(mContext, TaskDetailsActivity.class);
//                        intent.putExtra("no", message.replace("L:", ""));
//                        intent.putExtra("zt", "");
//                        intent.putExtra("type", 0);
//                        startActivityForResult(intent, 1002);
//                    }
                    return;
                } else if (!StringUtils.isEmpty(barcoderules) && message.contains("K:")) {
                    //库位码前缀
                    Intent intent = new Intent(mContext, KuwActivity.class);
                    intent.putExtra("no", message);
                    intent.putExtra("type", 1);
                    startActivityForResult(intent, 1001);
                    return;
                } else if (!StringUtils.isEmpty(barcoderules) && message.contains("WI")) {
                    //仓库盘点前缀
                    Intent intent = new Intent(mContext, Details2Activity.class);
                    intent.putExtra("kw", message);
                    intent.putExtra("zt", "");
                    intent.putExtra("type", 2);
                    startActivityForResult(intent, 1001);
                    return;
                } else if (!StringUtils.isEmpty(barcoderules) && message.contains("LQ")) {
                    //领取任务前缀
                    Intent intent = new Intent(mContext, Details2Activity.class);
                    intent.putExtra("kw", message);
                    intent.putExtra("zt", "");
                    intent.putExtra("type", 3);
                    startActivityForResult(intent, 1001);
                    return;
                } else {
                    if (message.contains("-")) {
                        String[] ms = message.split("-");
                        if (ms.length > 1) {
                            add_WMS_OutboundTask(ms[1]);
                        }
                    } else {
                        add_WMS_OutboundTask(message);
                    }
                }
            }
        });
    }

    private MediaPlayer mediaPlayer;

    public void ts_cg() {
        BaseActivity.this.runOnUiThread(() -> {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            mediaPlayer = MediaPlayer.create(mContext, R.raw.ts_cg);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.start();
        });
    }

    public void ts_cw() {
        BaseActivity.this.runOnUiThread(() -> {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            mediaPlayer = MediaPlayer.create(mContext, R.raw.ts_cw);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.start();
        });
    }

    //全局扫码,使用扫码领取任务
    private void add_WMS_OutboundTask(String no) {
        String R_Auth_Code = SPUtils.get(mContext, "auth", "") + "";
        Map data = new HashMap();
        data.put("no", no.replace("-", ""));
        data.put("sn", StringUtils.getDeviceSN(mContext));
        data.put("taskrecipient", SPUtils.get(mContext, "U_Name", "") + "");
        data.put("taskrecipientid", SPUtils.get(mContext, "U_Id", "") + "");//任务领取人id
        data.put("wh", U_DEPOT_ID + "");//作业仓库
        if (R_Auth_Code.contains("WMS_SCAN_ClAIMTICKET")) {
            data.put("authcode", "WMS_SCAN_ClAIMTICKET");
        } else {
            data.put("authcode", "");
        }
        String datStr = new Gson().toJson(data);
        HttpClient.getInstance().postData(CommonHttpConsts.add_WMS_OutboundTask, "add_WMS_OutboundTask")
                .headers("token", SPUtils.get(mContext, "token", "") + "")
                .upJson(datStr)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 || code == 1004) {
                            if (code == 1001) {
                                ToastUtil.show(msg);
                                ts_cg();
                            }
                            Intent intent = new Intent(mContext, Details2Activity.class);
                            intent.putExtra("no", no.replace("-", ""));
                            intent.putExtra("zt", "");
                            intent.putExtra("type", 2);
                            startActivityForResult(intent, 1001);
                        } else {
                            ToastUtil.show(msg);
                            ts_cw();
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    private void add_WMS_WarehouseEntryTask(String no) {
        String R_Auth_Code = SPUtils.get(mContext, "auth", "") + "";
        Map data = new HashMap();
        data.put("no", no);
        data.put("sn", StringUtils.getDeviceSN(mContext));
        data.put("taskrecipient", SPUtils.get(mContext, "U_Name", "") + "");
        data.put("taskrecipientid", SPUtils.get(mContext, "U_Id", "") + "");//任务领取人id
        data.put("wh", U_DEPOT_ID + "");//作业仓库
        if (R_Auth_Code.contains("WMS_IN_SCAN_ClAIMTICKET")) {
            data.put("authcode", "WMS_IN_SCAN_ClAIMTICKET");
        } else {
            data.put("authcode", "");
        }
        String datStr = new Gson().toJson(data);
        HttpClient.getInstance().postData(CommonHttpConsts.add_WMS_WarehouseEntryTask, "add_WMS_WarehouseEntryTask")
                .headers("token", SPUtils.get(mContext, "token", "") + "")
                .upJson(datStr)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 || code == 1004) {
                            if (code == 1001) {
                                ToastUtil.show(msg);
                                ts_cg();
                            }
                            Intent intent = new Intent(mContext, TaskDetailsActivity.class);
                            intent.putExtra("no", no);
                            intent.putExtra("zt", "");
                            intent.putExtra("type", 0);
                            startActivityForResult(intent, 1002);
                        } else {
                            ToastUtil.show(msg);
                            ts_cw();
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    protected void statusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.white));// 改变标题栏背景颜色
            window.setNavigationBarColor(getResources().getColor(R.color.black));//改变标题栏字体颜色
        }
    }

    protected void statusbar4() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//显示状态栏

        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    protected void network(boolean isConnect) {
        isConnected = isConnect;
    }

    // 请求权限
    public void requestPermissions(int requestCode) {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                ArrayList<String> requestPerssionArr = new ArrayList<>();
                int hasInternet = checkSelfPermission(Manifest.permission.INTERNET);
                if (hasInternet != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.INTERNET);
                }
                int read_phone_state = checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
                if (read_phone_state != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.READ_PHONE_STATE);
                }
                int read_external_storages = checkSelfPermission(READ_EXTERNAL_STORAGE);
                if (read_external_storages != PERMISSION_GRANTED) {
                    requestPerssionArr.add(READ_EXTERNAL_STORAGE);
                }
                int write_external_storages = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (write_external_storages != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                int request_install_packages = checkSelfPermission(Manifest.permission.REQUEST_INSTALL_PACKAGES);
                if (request_install_packages != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.REQUEST_INSTALL_PACKAGES);
                }

                // 是否应该显示权限请求
                if (requestPerssionArr.size() >= 1) {
                    String[] requestArray = new String[requestPerssionArr.size()];
                    for (int i = 0; i < requestArray.length; i++) {
                        requestArray[i] = requestPerssionArr.get(i);
                    }
                    requestPermissions(requestArray, requestCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean flag = false;
        for (int i = 0; i < permissions.length; i++) {
            if (PERMISSION_GRANTED == grantResults[i]) {
                flag = true;
            }
        }
    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        Configuration configuration = new Configuration();
        configuration.setToDefaults();
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return resources;
    }
}
